package org.jgs1904.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jgs1904.bean.ConditionBean;

/**
 * 生成查询条件和参数工具类
 * @author junki
 * @date 2020年4月1日
 */
public class ConditionUtil {
	
	private ConditionUtil() {};
	
	public static ConditionBean getCondition(Map<String, String[]> paramMap, Class<?> clazz, String tableName) {
		
		StringBuffer sql = new StringBuffer();
		ArrayList<Object> params = new ArrayList<>();
		
		for (String key : paramMap.keySet()) {
			
			if (key.startsWith("%") && key.endsWith("%")) {
				// title like '%xxx%'
				String filedName = key.replace("%", "");
				Field field = null;
				try {
					field = clazz.getDeclaredField(filedName);
				} catch (NoSuchFieldException | SecurityException e) {
				}
				if (field != null) {
					sql.append(" and ").append(tableName).append(".").append(filedName).append(" like ? ");
					params.add("%" + paramMap.get(key)[0] + "%");
				}
				
			} else if (key.startsWith("%")) {
				// title like '%xxx'
				String filedName = key.replace("%", "");
				Field field = null;
				try {
					field = clazz.getDeclaredField(filedName);
				} catch (NoSuchFieldException | SecurityException e) {
				}
				if (field != null) {
					sql.append(" and ").append(tableName).append(".").append(filedName).append(" like ? ");
					params.add("%" + paramMap.get(key)[0]);
				}
				
			} else if (key.endsWith("%")) {
				// title like 'xxx%'
				String filedName = key.replace("%", "");
				Field field = null;
				try {
					field = clazz.getDeclaredField(filedName);
				} catch (NoSuchFieldException | SecurityException e) {
				}
				if (field != null) {
					sql.append(" and ").append(tableName).append(".").append(filedName).append(" like ? ");
					params.add(paramMap.get(key)[0] + "%");
				}
				
			} else if (key.endsWith("%range")) {
				// create_time between 'xxx' and 'xxx'
				String filedName = key.replace("%range", "");
				Field field = null;
				try {
					field = clazz.getDeclaredField(filedName);
				} catch (NoSuchFieldException | SecurityException e) {
				}
				if (field != null && !StringUtils.isAnyBlank(paramMap.get(key)[0], paramMap.get(key)[1])) {
					sql.append(" and ").append(tableName).append(".").append(filedName).append(" between ? and ?  ");
					params.add(paramMap.get(key)[0]);
					params.add(paramMap.get(key)[1]);
				}
			} else {
				
				Field field = null;
				try {
					// 查询参数是否是实体类中的属性
					field = clazz.getDeclaredField(key);
				} catch (NoSuchFieldException | SecurityException e) {
					
				}
				if (field != null) {
					// 如果是实体中的属性，就拼接sql并保存参数
					sql.append(" and ").append(tableName).append(".").append(key).append(" = ? ");
					params.add(paramMap.get(key)[0]);
				}
			}
			
		}
		
		ConditionBean conditionBean = new ConditionBean(sql.toString(), params);
		
		return conditionBean;
	}
	
}
